package com.ruoyi.system.service.impl;

import com.ruoyi.common.config.SmsConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.AliyunSmsSender;
import cn.hutool.core.util.StrUtil;

import com.ruoyi.system.domain.TbPassenger;
import com.ruoyi.system.service.ITbPassengerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class SmsServerice {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ITbPassengerService passengerService;

    public Boolean sendCode(String phone) {
        // 验证手机号格式
        if (StrUtil.isBlank(phone) || !isValidPhone(phone)) {
            throw new RuntimeException("手机号格式不正确");
        }

        // 检查是否在60秒内重复获取验证码
        String recentKey = Constants.Redis_SMS_RECENT + phone;
        if (redisCache.hasKey(recentKey)) {
            throw new RuntimeException("请勿频繁获取验证码，请稍后再试");
        }

        //获取短信验证码过期时间
        Integer codeExpire = 5;
        Integer code = randomCount(111111, 999999);
        Boolean aBoolean = AliyunSmsSender.sendSmsCode(phone, code);
        if (!aBoolean) {
            throw new RuntimeException("发送短信失败，请联系后台管理员");
        }
        
        // 将验证码存入redis
        redisCache.setCacheObject(Constants.Redis_SMS + phone, code, codeExpire, TimeUnit.MINUTES);
        // 设置60秒内不能重复获取验证码
        redisCache.setCacheObject(recentKey, "1", 60, TimeUnit.SECONDS);
        
        return true;
    }

    public static Integer randomCount(Integer start, Integer end) {
        return (int) (Math.random() * (end - start + 1) + start);
    }


    // 中国大陆手机号正则（简单版）
    private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";

    public static boolean isValidPhone(String phone) {
        if (phone == null || phone.trim().isEmpty()) {
            return false;
        }
        Pattern pattern = Pattern.compile(PHONE_REGEX);
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }

    public Boolean bindTheVerificationCodeOfTheMobilePhoneNumber(String phone) {
        // 验证手机号格式
        if (StrUtil.isBlank(phone) || !isValidPhone(phone)) {
            throw new RuntimeException("手机号格式不正确");
        }

        // 检查是否在60秒内重复获取验证码
        String recentKey = Constants.Redis_SMS_BIND_RECENT + phone;
        if (redisCache.hasKey(recentKey)) {
            throw new RuntimeException("请勿频繁获取验证码，请稍后再试");
        }

        //获取短信验证码过期时间
        Integer codeExpire = 5;
        Integer code = randomCount(111111, 999999);
        Boolean aBoolean = AliyunSmsSender.sendSmsCode(phone, code);
        if (!aBoolean) {
            throw new RuntimeException("发送短信失败，请联系后台管理员");
        }

        // 将验证码存入redis
        redisCache.setCacheObject(Constants.Redis_BIND_SMS + phone, code, codeExpire, TimeUnit.MINUTES);
        // 设置60秒内不能重复获取验证码
        redisCache.setCacheObject(recentKey, "1", 60, TimeUnit.SECONDS);

        return true;
    }

    public void verifyTheBoundMobilePhoneNumber(String phone, String code,Long userId) {

        String redisSmsCode = redisCache.getCacheObject(Constants.Redis_BIND_SMS + phone) +"";
        //短信
        if (!code.equals(redisSmsCode)){

            throw new BaseException("验证码错误");
        }
        TbPassenger passenger=this.passengerService.selectTbPassengerById(userId);
        if(passenger!=null){
            passenger.setPassengerTel(phone);
            this.passengerService.updateTbPassenger(passenger);

        }
    }
}
